<script setup lang="ts">

import { computed, ref, toRefs } from 'vue';
import Square from './Square.vue';
import useWinner, { DefaultSquares, Squares } from '../algotithm/check';

interface IProps {
  squares: (string | null)[]
}

const props = withDefaults(defineProps<IProps>(), {
  squares: () => DefaultSquares,
});

const emit = defineEmits<{(e:'update:squares', s:Squares):void
}>();

const nextPlayer = ref<string>('X');
const { squares } = toRefs<IProps>(props);
const { winner } = useWinner(squares);

function squareClick(index:number):void {
  if (!winner.value) {
    squares.value[index] = nextPlayer.value;
    nextPlayer.value = nextPlayer.value === 'X' ? 'O' : 'X';
    emit('update:squares', squares.value);
  }
}

const status = computed<string>(() => {
  if (winner.value) {
    return `赢家是: ${winner.value}`;
  } if (squares.value.indexOf(null) === -1) {
    return '平局';
  }
  return `下一个玩家是:${nextPlayer.value}`;
});
</script>

<template>
  <div>
    <div class="status">{{status}}</div>
    <div class="board-row" v-for="i in 3" :key="i">
      <Square v-for="j in 3" :key="(i-1)*3+j-1"
              :value="squares[(i-1)*3+j-1]"
              @click="squareClick((i-1)*3+j-1)"
      ></Square>
    </div>
  </div>
</template>

<style scoped>
.board-row:after {
  clear: both;
  content: "";
  display: table;
}

.status {
  margin-bottom: 10px;
}
</style>
